<?php

namespace App\Admin\Forms;


use App\Admin\Renderable\GoodsRenderable;
use App\Models\SwtGood;
use App\Models\SwtGoodQuantity;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Form as NestedForm;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class GoodLossForm extends Form implements LazyRenderable
{
    use LazyWidget;
    public function handle(array $input)
    {
        try{
            $goods = $input['goods'] ;
            $num = 0;
            DB::beginTransaction();

            foreach ($goods as $good) {
                $goods_quantity = SwtGoodQuantity::where(['goods_id'=>$good['good_id']])->first();
                if(!$goods_quantity->increment('loss_quantity',$good['loss_quantity'])){
                    $num ++;
                }
                if(!$goods_quantity->decrement('normal_quantity',$good['loss_quantity'])){
                    $num ++;
                }
            }
            if($num > 0){
                throw new \Exception('编辑失败');
            }

            Db::commit();
            return $this->response()->success('编辑成功')->refresh();
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->response()->error('编辑失败');
        }
    }

    public function form()
    {

        $this->hasMany('goods','添加商品',function ($form) {

            $form->row(function (NestedForm\Row $form) {
                $form->width(4)
                    -> selectTable('good_id','商品名')
                    -> title('商品表')
                    -> from(GoodsRenderable::make())
                    -> rules('required', [ 'required' => '商品名不能为空' ])
                    -> model(SwtGood::class, 'id', 'goods_name')
                    -> required();

                $form ->width(3)
                    -> text('loss_quantity','损耗数量')
                    -> type('number')
                    -> rules('required', [ 'required' => '数量不能为空','min'=>0])
                    -> required();


            });

        });


    }

}
